package com.exam.controller;

import com.exam.entity.ApiResult;
import com.exam.util.ApiResultHandler;
import com.exam.util.ImgUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
@Api(tags = "图片上传")
public class FileController {

    @Autowired
    private ImgUtils imgUtils;

    /**
     * 上传图片题目
     *
     * @return
     */
    @PostMapping( "/uploadImages")
    @ApiOperation(value = "上传图片题目", notes = "上传图片题目")
    public ApiResult uploadImages(@RequestParam(value = "file") MultipartFile file) {

        if (file.isEmpty()) return ApiResultHandler.buildApiResult(501,"文件不存在",null);
        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        String filePath = "D://temp//"; // 上传后的路径,即本地磁盘
        fileName = UUID.randomUUID() + suffixName; // 新文件名
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //本地目录和生成的文件名拼接，这一段存入数据库
        String filename = "/temp/" + fileName;
        String imgUrl = "http://"+imgUtils.getHostIp()+":" + imgUtils.getPort()  +filename;
        log.info("图片路径：{}" , imgUrl);
        return ApiResultHandler.success(imgUrl);
    }


}
